﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.ServiceModel;
using Teenusekiht;

public partial class Account_Login : System.Web.UI.Page
{
    IService1 sc = new ChannelFactory<IService1>("Serv").CreateChannel();

    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterHyperLink.NavigateUrl = "~/Kohvik/Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

    }

    protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e) 
    {
        string user = LoginUser.UserName;
        string pass = LoginUser.Password;

        //string passHashDB = FormsAuthentication.HashPasswordForStoringInConfigFile("kristjan", "SHA1");
        //Response.Write(passHashDB);
        //Debug.Print("hash: " + passHashDB);

        IService1 sc = new ChannelFactory<IService1>("Serv").CreateChannel();
        int? integ = sc.AuthendiKasutaja(user, pass, Rakendus.RAKENDUSE_KOOD);

        bool loggedIn = true;

        if (integ != null)
        {
            if (Session["sess"] == null) Session["sess"] = SessionStatic.CreateSession();
            SessionData sesDat = SessionStatic.GetData((int)Session["sess"]);
            sesDat.UserId = integ;
            sesDat.UserName = sc.AnnaKasutajaIdJargi((int)integ, Rakendus.RAKENDUSE_KOOD);
            sesDat.UserDisp = sesDat.UserName;
            KohvikuKasutajaRoll[] roles = sc.KasutajaKohvikuRollid((int)integ, Rakendus.RAKENDUSE_KOOD);
            sesDat.AddRoles(roles);
            loggedIn = true;
        }
        else
        {
            loggedIn = false;
        }
        
        sc.Dispose();

        e.Authenticated = loggedIn;
    }

    protected void LoginUser_LoginError(object sender, EventArgs e)
    {
        LoginUser.FailureText = "Sisselogimine ebaõnnestus. Proovi uuesti.";
    }

    protected void UserName_Load(object sender, EventArgs e)
    {
        (sender as TextBox).Focus();
    }

    protected void btnSaadaUusParool_Click(object sender, EventArgs e)
    {
        string email = sc.AnnaKasutajaMeiliAadress(tb_MeiliAadress.Text, Rakendus.RAKENDUSE_KOOD);

        string newPassword = Membership.GeneratePassword(9, 0);
        lblCheck.Text = newPassword;
    }

}
